import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import AdminLayout from '../views/AdminLayout.vue'
import Dashboard from '../views/Dashboard.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/admin',
    component: AdminLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/admin/dashboard'
      },
      {
        path: '/admin/dashboard',
        name: 'Dashboard',
        component: Dashboard
      },
      {
        path: '/admin/stores',
        name: 'Stores',
        component: () => import('../views/admin/Stores.vue')
      },
      {
        path: '/admin/users',
        name: 'Users',
        component: () => import('../views/admin/Users.vue')
      },
      {
        path: '/admin/distributors',
        name: 'Distributors',
        component: () => import('../views/admin/Distributors.vue')
      },
      {
        path: '/admin/commission-rates',
        name: 'CommissionRates',
        component: () => import('../views/admin/CommissionRates.vue')
      },
      {
        path: '/admin/activities',
        name: 'Activities',
        component: () => import('../views/admin/Activities.vue')
      },
      {
        path: '/admin/withdrawals',
        name: 'Withdrawals',
        component: () => import('../views/admin/Withdrawals.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('admin_token')
  
  if (to.meta.requiresAuth !== false && !token) {
    next('/login')
  } else if (to.path === '/login' && token) {
    next('/admin/dashboard')
  } else {
    next()
  }
})

export default router 